package departmentpostionvalidator

import (
	"fmt"
	"time"
	"yunj/pkg/yunj/app/enum/admin/departmentenum"
	"yunj/pkg/yunj/app/enum/stateenum"
	"yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/util"

	"github.com/worklz/go-validate"
)

type DepartmentPostion struct {
	validate.Validator
}

func (v *DepartmentPostion) HandleDatas(datas map[string]interface{}, scene string) (err error) {
	if scene == "FormSubmit" {
		err = v.HandleDatasByFormSubmit(datas)
		if err != nil {
			return
		}
	}
	return
}

func (v *DepartmentPostion) HandleDatasByFormSubmit(datas map[string]interface{}) (err error) {
	currTime := time.Now().In(time.Local)
	datas = util.MapFloat64ToUints(datas)
	dbDepartmentPostion := &model.AdminDepartmentPostion{
		Type: util.MapKeyValue(datas, "type", departmentenum.POSTION_TYPE_OTHER),
	}
	// id
	var id uint64
	if idRaw, exists := datas["id"]; exists {
		if idVal, err := util.ToUint64(idRaw); err == nil && idVal > 0 {
			id = idVal
		}
	}
	// postion_id
	postionIdRaw, exists := datas["postion_id"]
	if !exists {
		err = fmt.Errorf("请选择岗位！")
		return
	}
	postionId, err := util.ToUint64(postionIdRaw)
	if err != nil || postionId <= 0 {
		err = fmt.Errorf("岗位数据异常！请重新选择")
		return
	}
	dbDepartmentPostion.PostionId = postionId
	if id > 0 {
		// 编辑
		dbDepartmentPostion.Id = id
	} else {
		// 新增
		dbDepartmentPostion.CreatedAt = &currTime
		dbDepartmentPostion.State = stateenum.NORMAL
	}
	datas["dbDepartmentPostion"] = dbDepartmentPostion
	return
}
